#include "Resource.h"
#include "ResourceType.h"
#include "Game.h"

#include "../tools/StringTokenizer.h"
#include "../tools/Log.h"

using namespace std;

Resource::Resource(ResourceType *type, int quantity) : type(type), quantity(quantity) {}

/**	Takes a string of the form ResourceTypeID1:Qty1,ResourceTypeID2:Qty2,... and returns a
	vector of pointers to resources. Verifies that the required resources type exists in the
	provided game. Used for reading required resources from UnitType and BuildingType
	configuration files into an array.
*/
vector <Resource> Resource::load_from_string(Game *, char *resource_string)
{
	vector <Resource> resources;

	StringTokenizer tok = StringTokenizer(resource_string, ",");
	while (tok.hasMoreTokens())
	{
		unsigned int resource_id, resource_amount;
		sscanf(tok.nextToken().c_str(), "%u:%u", &resource_id, &resource_amount);
		
		// Find resource type
		ResourceType *rt = NULL;//game->get_resource_type(resource_id);
		
		if (!rt) {
			lout << "WARNING: Resource - Configuration file specified a required resource (" << resource_id
				<< ") that doesn't exist." << endl;
			return resources;
		}
		
		// Find existing resource, if it exists (means it was provided twice)
		for (unsigned int i = 0; i < resources.size(); i ++)
			if (resources[i].type == rt) {
				lout << "WARNING: Resource - Configuration file specified a required resource (" << resource_id << ") twice." << endl;
				return resources;
			}
		
		resources.push_back(Resource(rt, resource_amount));
	}
	
	return resources;
}
